package com.android.semita.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.semita.model.ShippedLocationItem;

public class ShippedLocationController {

	public ShippedLocationItem getShippedLocationFromJSON(String JSONString) {
		ArrayList<ShippedLocationItem> ShippedLocationItems = new ArrayList<ShippedLocationItem>();

		try {

			JSONObject shiplocationObj = new JSONObject(JSONString);

			JSONArray shiplocationArray = shiplocationObj.getJSONArray("ShippedLocation");

			for (int i = 0; i <= shiplocationArray.length() - 1; i++) {
				JSONObject ItemObject = shiplocationArray.getJSONObject(i);

				ShippedLocationItem ShipLocation = new ShippedLocationItem();
				ShipLocation.setInvoiceNo(ItemObject.getString("InvoiceNo"));
				Date date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a",
						Locale.ENGLISH).parse(ItemObject
						.getString("TargetDate"));
				ShipLocation.setTargetDate(date);// 1/1/2013 12:00:00 AM
				ShipLocation.setAddress(ItemObject.getString("Address"));
				String AddressGPS = ItemObject.getString("AddressGPS");
				String[] parts = AddressGPS.split(",");
				ShipLocation.setAddressGPS(AddressGPS);
				ShipLocation.setLatitude(Double.parseDouble(parts[0]));
				ShipLocation.setLongitude(Double.parseDouble(parts[1]));
				ShipLocation.setInvoiceStatus(ItemObject
						.getString("InvoiceStatus"));
				ShipLocation.setCustomerName(ItemObject
						.getString("CustomerName"));

				ShippedLocationItems.add(ShipLocation);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (ShippedLocationItems.size() != 0)
			return ShippedLocationItems.get(0);
		else
			return null;

	}
}
